﻿(function () {
    "use strict";

    var directives = angular.module("appDirectives", []);
    directives.directive("bookList", function()
    {
        return {
            restrict: "E",
            templateUrl: "/templates/booklist",
            controller: function ($scope, $rootScope, $filter, ngTableParams, BookStoreService) {
                function update() {
                    BookStoreService.getBookList().then(function (result) {
                        $scope.books = result.data;
                        $scope.bookTable.reload();
                    });
                }

                $scope.book = {};
                $scope.books = [];
                $scope.orderedBooks = [];

                $scope.$on("dataPushed", function() {
                    update();
                });

                $scope.$on("refreshData", function() {
                    update();
                });

                $scope.bookTable = new ngTableParams({
                    page: 1, 
                    count: 10,
                    sorting: sessionStorage.getItem("ngBook-sorting") ? JSON.parse(sessionStorage.getItem("ngBook-sorting")) : {title:"asc"}
                }, {
                    total: $scope.books.length,
                    getData: function ($defer, params) {
                        var orderedData = params.sorting() ?
                                            $filter("orderBy")($scope.books, params.orderBy()) :
                                            $scope.books;

                        $scope.orderedBooks = orderedData;
                        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    }
                });
                update();

                $scope.$watch('bookTable.$params.sorting', function () {
                    sessionStorage.setItem("ngBook-sorting", JSON.stringify($scope.bookTable.$params.sorting));
                });

                this.get = function(id) {
                    return BookStoreService.getBook(id);
                };

                this.getList = function() {
                    this.books = BookStoreService.getBookList();
                };

                this.add = function(book) {
                    return BookStoreService.addBook(book).then(function(res) {
                        $(".modal").modal("hide");
                    });
                };

                this.peekBook = function (book) {
                    $scope.book = book;
                    $scope.$broadcast("editBook", book);
                    $scope.$emit("editBook", book);
                };

                this.newBook = function () {
                    $scope.$broadcast("addBook");
                };

                this.remove = function(index) {
                    var book = $scope.orderedBooks[index];
                    BookStoreService.removeBook(book).then(function(res) {
                        $scope.books.splice($scope.books.indexOf(book), 1);
                        $scope.bookTable.reload();
                    });
                };

                this.removeAuthor = function(authorIndex, book, delay) {
                    if ((book.authors.length > 1)) {
                        if (!delay) {
                            book.authors.splice(authorIndex, 1);
                            BookStoreService.modifyBook(book);
                        } else {
                            book.authors.splice(authorIndex, 1);
                        }
                    }
                };
            },
            controllerAs: "BookListCtrl"
        }
    });

    directives.directive("bookAddDialog", function () {
        return {
            restrict: "E",
            templateUrl: "templates/BookItemAddDialog"
        };
    });

    directives.directive("bookEditDialog", function () {
        return {
            restrict: "E",
            templateUrl: "templates/BookItemEditDialog"
        };
    });

    directives.directive("coverUpload", ["$parse", function ($parse) {
        return {
            restrict: "A",
            link: function (scope, element, attrs) {
                var model = $parse(attrs.coverUpload),
                    setter = model.assign;

                element.bind("change", function () {
                    scope.$apply(function () {
                        setter(scope, element[0].files[0]);
                    });
                });

                scope.$on("bookEdited", function () {
                    element.val(null); 
                });
            }
        };
    }]);
})()